<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    @dialog-close="dialogClose"
    :dialogWidth="dialogWidth"
  >
    <template #searchPanel>
      <!-- {{allStores}} -->
      <el-row>
        <el-col :span="12">调拨申请信息</el-col>
        <el-divider content-position="center"></el-divider>
      </el-row>
      <form-create v-model="cusutomerFormModel" :rule="rule" :option="option" />
    </template>

    <template #contentPanel>
      <el-row>
        <el-col :span="12">调拨车型列表</el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" @click="addCar"
            ><i class="el-icon-plus"></i> 添加调拨车型</el-button
          >
        </el-col>
      </el-row>
      <el-divider content-position="center"></el-divider>

      <data-table
        :value="tableData"
        :has-action="true"
        :table-column-attributes="tableColumnAttributes"
        :width="160"
        :isShowPage="false"
      >
        <template #action="{ $index }">
          <i
            class="el-icon-delete"
            title="删除"
            v-permission="'xcAllot:del'"
            style="color: red; margin-left: 15px; cursor: pointer"
            @click="deleteCarInfo($index)"
          ></i>
        </template>
      </data-table>
      <div>
        调拨总金额：<span style="color: rgba(228, 57, 60, 100); font-size: 28px"
          >¥{{ totalPriceFun }}</span
        >
        &nbsp;&nbsp;&nbsp;&nbsp;总数：<span
          style="color: rgba(16, 16, 16, 100); font-size: 28px"
          >{{ tableData.length }}</span
        >
      </div>
      <div class="text-right mt10">
        <el-button
          type="success"
          v-permission="'xcAllot:update'"
          @click="saveUpdate"
          >保存</el-button
        >
      </div>
    </template>

    <template #dialog>
      {{ tableDataMapObj }}
      <SelectCarModel @getList="getList" :store-id="storeId" />
    </template>
  </base-layout>
</template>

<script>
import baseMixin from '@/mixins/base'
import {
  addData,
  updateData,
  findById,
} from '@/api/pre-sale/newCarStock/transferApply'
import { getDict } from '@/utils/index'
import { rulesForm } from './rules'
import { mapGetters } from 'vuex'
import { transferLabelAndValue } from '@/utils/pre-sale'
export default {
  props: ['id'],
  mixins: [
    baseMixin({
      format(res) {
        return res.map((data) => {
          return data
        })
      },
    }),
  ],
  computed: {
    ...mapGetters(['stores', 'allStores']),
    totalPriceFun() {
      return this.tableData.reduce((pre, current) => {
        return +current.guidePrice + +pre
      }, 0)
    },
  },
  data() {
    return {
      tableDataMapObj: [],
      cusutomerFormModel: {},
      rule: rulesForm,
      option: {
        //显示表单重置按钮
        resetBtn: false,
        submitBtn: false,
      },
      dialogTitle: '车型选中',
      activeName: 'first',
      currentPage: 0,
      pageSize: 5,
      totalCount: 0,
      dialogWidth: '1200px',
      disabledType: false,
      tableData: [],
      totalPrice: 0,
      dict: {},
      getDict,
      brandId: '',
      tableColumnAttributes: [
        {
          name: '品牌',
          value: 'brandName',
          type: 'text',
        },
        {
          name: '车系',
          value: 'seriesName',
          type: 'text',
          width: '150px',
        },
        {
          name: '车型',
          value: 'modelName',
          type: 'text',
          width: '350px',
        },
        {
          name: '车身色',
          value: 'outColor',
          type: 'input',
        },
        {
          name: '内饰色',
          value: 'inColor',
          type: 'input',
        },
        {
          name: '车顶色',
          value: 'roofColor',
          type: 'input',
        },
        // {
        //   name: '增配件及价格明细',
        //   value: 'timeType',
        //   type: 'text',
        // },
        // {
        //   name: '前装及价格明细',
        //   value: 'carModelName',
        //   type: 'text',
        // },
        {
          name: '采购单价(元)',
          value: 'guidePrice',
          type: 'inputNumber',
        },
        {
          name: '备注',
          value: 'remark',
          type: 'input',
        },
      ],
    }
  },
  async created() {},
  methods: {
    tableDataMap() {
      let listIds = []
      this.tableData.map((item) => {
        listIds = [...listIds, item.id]
      })
      this.tableDataMapObj = [...new Set(listIds)]
    },
    handleClick() {},
    async saveUpdate() {
      this.cusutomerFormModel.submit(async (formData) => {
        const params = {
          ...formData,
          carList: this.tableData,
          amount: this.totalPriceFun,
        }
        if (this.id) {
          await updateData({ ...params, id: this.id })
        } else {
          await addData(params)
        }
        this.$router.push({ name: 'transferApply' })
      })
    },
    deleteCarInfo(index) {
      this.tableData.splice(index, 1)
    },
    addCar() {
      const storeId = this.cusutomerFormModel.getValue('sourceStoreId')
      if (!storeId) {
        this.$message.error('请选择来源门店后添加车型')
        return
      }
      this.storeId = storeId
      this.dialogVisible = true
    },
    getList(selection) {
      let tableList = []
      selection.forEach((item) => {
        if (!this.tableDataMapObj.includes(item.id)) {
          item.modelId = item.id
          tableList.push(item)
        }
      })
      this.tableData.push(...tableList)
      this.tableDataMap()
      this.dialogClose()
    },
  },

  async mounted() {
    setTimeout(() => {
      this.cusutomerFormModel.updateRules({
        storeId: {
          options: transferLabelAndValue(this.stores, ['storeName', 'id']),
        },
        sourceStoreId: {
          options: transferLabelAndValue(this.allStores, ['storeName', 'id']),
        },
      })
    }, 800)

    if (this.id) {
      const { data } = await findById(this.id)
      this.cusutomerFormModel.setValue(data)
      this.tableData = data.carList
      this.tableDataMap(data.carList)
      this.getList(data.carList)
    }
  },
}
</script>

<style lang="scss" scoped>
.mt10 {
  margin-top: 10px;
}
.ml10 {
  margin-left: 10px;
}
</style>
